package com.bayi.storage.network;

import static com.bayi.storage.network.entity.LoggerInterceptor.NETWORKURL;

import com.bayi.storage.utils.LogUtil;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.functions.Func1;

/**
 * @ProjectName: APPTest
 * @Package: com.ucity.apptest.service
 * @ClassName: RetryWithDelay
 * @Description: java类作用描述
 * @Author: .
 * @CreateDate: 2020/4/8 15:35
 */
public class RetryWithDelay implements Func1<Observable<? extends Throwable>, Observable<?>> {

    private final int maxRetries;
    private final int retryDelayMillis;
    private int retryCount;

    public RetryWithDelay(int maxRetries, int retryDelayMillis) {
        this.maxRetries = maxRetries;
        this.retryDelayMillis = retryDelayMillis;
    }

    @Override
    public Observable<?> call(Observable<? extends Throwable> attempts) {
        return attempts
                .flatMap((Func1<Throwable, Observable<?>>) throwable -> {
                    if (++retryCount <= maxRetries) {
                        // When this Observable calls onNext, the original Observable will be retried (i.e. re-subscribed).
                        LogUtil.e(NETWORKURL, "get error, it will try after " + retryDelayMillis
                                + " millisecond, retry count " + retryCount);
                        return Observable.timer(retryDelayMillis,
                                TimeUnit.MILLISECONDS);
                    }
                    // Max retries hit. Just pass the error along.
                    return Observable.error(throwable);
                });
    }
}
